#include "StdAfx.h"
#include "mlsscanner.h"
#include "mlschain.h"

CString CMLSChain::ErrMsg[] =
{_T("No error"),_T("Can't open file"),_T("Too long chain"),_T("Item not pointing to the right previous")
,_T("Last Item not pointing to first")
};

CString CMLSChain::GetError()
{
	return ErrMsg[(int)Error];
}

CMLSChain::CMLSChain(void):Count(0),Error(mlsce_None)
{
	for(int n=0;n<MAX_ITEMS;n++)pItem[n]=NULL;
}

CMLSChain::CMLSChain(CString istart):Count(NULL),Error(mlsce_None)
{
	for(int n=0;n<MAX_ITEMS;n++)pItem[n]=NULL;
	SetStartDoc(istart);
}

CMLSChain::~CMLSChain(void){Clean();}

void CMLSChain::SetStartDoc(CString value)
{
	DocsPath.Empty();
	int n = value.ReverseFind('\\');
	if(n==-1) return;
	StartDoc = value.Right(value.GetLength()-n-1);
	DocsPath = value.Left(n+1);
}

void CMLSChain::Clean(void)
{
	for(int n=0;n<Count;n++)
	{
		delete pItem[n];
		pItem[n]=NULL;
	}
	Count = 0;
}

BOOL CMLSChain::CreateItem(int n,CString FilePath,CString FileName)
{
	pItem[n] = new MLSChainItem(FileName);
	CMLSScanner MLSFile;
	if(MLSFile.Open(FilePath+FileName))
	{
		pItem[n]->prevname = MLSFile.GetPrevDoc();
		pItem[n]->nextname = MLSFile.GetNextDoc();
		return TRUE;
	}
	else
	{
		delete pItem[n];
		Error = CMLSChain::mlsce_File;
		return FALSE;
	}
}

int CMLSChain::Find(CString FileName)
{
	for(int n=0;n<Count;n++)
	{
		if(FileName.CompareNoCase(pItem[n]->thisname)==0) return n;
    }
	return -1;
}

BOOL CMLSChain::LoadChain()
{
	Clean();
	if(StartDoc.IsEmpty()) return FALSE;
	for(CString next = StartDoc;!next.IsEmpty();Count++)
	{
		if(!CreateItem(Count,DocsPath,next)) return FALSE;
		pItem[Count]->prev = Find(pItem[Count]->prevname);
		pItem[Count]->next = Find(pItem[Count]->nextname);
		if(pItem[Count]->next!=-1) {Count++;break;}
		if(Count==39) {Error = CMLSChain::mlsce_BigChain;return FALSE;}
		next = pItem[Count]->nextname;
	}
	return CheckChain();
}
BOOL CMLSChain::CheckChain()
{
	if(pItem[Count-1]->next>0)
	{Error = CMLSChain::mlsce_Last;return FALSE;}
	for(int n=0; n<Count-1; n++)
		if(pItem[n+1]->prev!=n)
		{Error = CMLSChain::mlsce_Prev;return FALSE;}
	return TRUE;
}
BOOL CMLSChain::MoveAll(CString TargetPath)
{
	for(int n=0; n<Count; n++)
		MoveFile(GetItemPath(n), TargetPath);

	return TRUE;
}